package com.kevin.state.machine.transaction;

import com.kevin.state.machine.enums.Action;
import com.kevin.state.machine.enums.State;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.List;

@Getter
@Setter
@ToString
@Accessors(chain = true)
public class StateMachine {

    // 状态列表，保存状态
    private List<Transaction<String>> transactionList;
    // 当前状态
    private State currentState;

    public StateMachine(State state) {
        this.currentState = state;
        transactionList = new ArrayList<>();
    }

    // 添加数据
    public Transaction<String> add() {
        Transaction<String> transaction = new Transaction<>();
        transactionList.add(transaction);
        return transaction;
    }

    // 状态转换
    public void execute(Action action) {
        for (Transaction<String> transaction : transactionList) {
            if (currentState == transaction.getCurrentState() &&
                    action == transaction.getAction()) {
                transaction.getEvent().handle();
                currentState = transaction.getNextState();
                return;
            }
        }
    }

}
